<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="utf-8">
<style>
section { margin-bottom: 30px} 
section header {
	font-weight: bolder;
	padding-bottom: 10px;
} 
.amount {
	width: 200px;
	text-align: right;
	border: 1px solid #aaa;
	background-color: #eee;
	padding: 3px 8px;
} 
.msg {
	width: 80%;
	padding: 8px;
	margin-bottom: 20px; 
} 
.normalMsg {background: #dfb} 
.errorMsg {background: #ffbeb8}
  
[v-cloak]{display:none } /* to avoid vue render flash */  

</style>

<script src="/js/vue.js"></script>
<script src="/js/jquery-1.11.3.min.js"></script>
<script src="/js/jquery-ajax-ext.js"></script>
<script src="/js/gosqlgo.js"></script>
</head>
<body>
    <script> document.write($java(`return new WebBox("/WEB-INF/menu.html");`)); </script>
    <h2>Transaction demo, use Vue</h2>

	<div v-cloak id="vm">
		<div id="msgid" :class="['msg', {normalMsg:hasNormalMsg, errorMsg: hasErrorMsg }]">{{message}}</div>
		<section>
			<header>Account A</header>
			<div id="A" class="amount">{{aAmount}}</div>
		</section>
		<section>
			<header>Account B</header>
			<div id="B" class="amount">{{bAmount}}</div>
		</section>

		<section>
			<header>Transfer</header>
			<form onsubmit="return false" action="##" method="post">
				<input id="amount" name="amount" value="100" class="amount">
				<button name="btnA2B" value="true" onclick="transfer('A','B',$('#amount').val())">
				    From account A to account B</button>
				<button name="btnB2A" value="true" onclick="transfer('B','A',$('#amount').val())">
				    From account B to account A</button>
			</form>
		</section>
	</div>
	<script>
	  var vm= new Vue({
		  el: '#vm',
		  data: { 
			  hasNormalMsg: false,
			  hasErrorMsg: false,
			  message: '', 
			  aAmount: $qryObject(`select amount from account where id=? and amount>=?`, 'A',0),
			  bAmount: $qryObject(`select amount from account where id=? and amount>=?`, 'B',0) 
		  }
		})
	
	  function transfer(from, to, money){ 
		var rst = $$javaTx(`
		int money = Integer.parseInt($3);
		if (money <= 0)
		     return new JsonResult(0, "Error: Illegal input.");
		Account a = new Account().setId($1).load();
		if (a.getAmount() < money)
		     return new JsonResult(0, "Error:No enough balance!");
		Account b = new Account().setId($2).load();
		a.setAmount(a.getAmount() - money).update();
		b.setAmount(b.getAmount() + money).update();
		    return new JsonResult(200, "Transfer success!").setDataArray(a.getAmount(), b.getAmount());
        `, from,to,money);
		
        vm.message=rst.msg;
		if(rst.code==200) { 
				  vm.hasNormalMsg= true;  
				  vm.hasErrorMsg =false;
		 	      vm.aAmount=rst.data[0];
		 	      vm.bAmount=rst.data[1]; 
			  } else {  
				  vm.hasNormalMsg= false; 
				  vm.hasErrorMsg = true;
			  } 
	   }
	</script>
</body>
</html>